package com.laicunba.event.listener;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.constant.FinancingTargetConstant;
import com.laicunba.event.PaySuccessEvent;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.FinancingTargetDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.UserService;
import com.laicunba.service.accounting.RewardBidService;
import com.laicunba.util.StringUtil;

@Component
public class ChineseValentineListener implements ApplicationListener<PaySuccessEvent> {
	private static final Logger LOG = Logger.getLogger(ChineseValentineListener.class);
	@Autowired
	private UserService userService;
	@Autowired
	private RegistryService registryService;
	@Autowired
	private FinancingTargetService financingTargetService;
	@Autowired
	private RewardBidService rewardBidService;

	@Override
	public void onApplicationEvent(PaySuccessEvent event) {
		try {
			FinancingTargetBidDO bidDO = (FinancingTargetBidDO) event.getSource();
			RegistryDO registryDO = registryService.get(RegistryDO.class, "act.chinese-valentine.open");
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(bidDO != null && bidDO.getType().equalsIgnoreCase("CPB") && registryDO != null && new Date().compareTo(sdf.parse("2016-08-05 00:00:00")) >= 1 && new Date().compareTo(sdf.parse("2016-08-11 00:00:00")) < 1) {
				RegistryDO rewardCountRegistry = null;
				LOG.info(String.format("【七夕活动】用户投资送体验金，订单id为[%s],userId=[%s],标的id为[%s],标的类型为[%s],购买金额为[%s],payMark为[%s],下单时间为[%s],",bidDO.getId(), bidDO.getBidUserId(),bidDO.getFinancingTargetId(),bidDO.getType(),bidDO.getBuyAmount(),bidDO.getPayMark(),bidDO.getPayTime()));
				
				// 新用户首次投资并成功发放体验金，增加邀请人的奖励次数
				if(userService.countBidTimesHasBankInfo(bidDO.getBidUserId()) == 1 && grantExperienceMoney(bidDO)) {
					LOG.info(String.format("【七夕活动】新用户首次投资，给邀请人增加奖励次数，userId=[%s]", bidDO.getBidUserId()));
					UserDO inviter = userService.findInviteUser(bidDO.getBidUserId());
					if(inviter != null && StringUtil.isNotEmpty(inviter.getId())) {
						rewardCountRegistry = registryService.get(RegistryDO.class, "u." + inviter.getId() + ".qixi.reward.count");
						if(rewardCountRegistry != null) {
							rewardCountRegistry.setVal(String.valueOf(Integer.valueOf(rewardCountRegistry.getVal()) + 1));
							registryService.updateSkipCheckOwner(rewardCountRegistry);
						} else {
							rewardCountRegistry = new RegistryDO();
							rewardCountRegistry.setId("u." + inviter.getId() + ".qixi.reward.count");
							rewardCountRegistry.setVal("1");
							registryService.create(rewardCountRegistry);
						}
					}
				} else {
					rewardCountRegistry = registryService.get(RegistryDO.class, "u." + bidDO.getBidUserId() + ".qixi.reward.count");
					// 用户有奖励次数并成功发放体验金，次数减1
					if(rewardCountRegistry != null && Integer.valueOf(rewardCountRegistry.getVal()) > 0 && grantExperienceMoney(bidDO)) {
						LOG.info(String.format("【七夕活动】用户投资赠送体验金，奖励次数减1，userId=[%s],原奖励次数为[%s]", bidDO.getBidUserId(), rewardCountRegistry.getVal()));
						rewardCountRegistry.setVal(String.valueOf(Integer.valueOf(rewardCountRegistry.getVal()) - 1));
						registryService.updateSkipCheckOwner(rewardCountRegistry);
					}
				}
			}
		} catch (Exception e) {
			LOG.error("【七夕活动】体验金发放出错了", e);
		}
	}
	
	private boolean grantExperienceMoney(FinancingTargetBidDO bid) {
		if(bid != null && StringUtil.isNotEmpty(bid.getFinancingTargetId())) {
			FinancingTargetDO target = financingTargetService.get(FinancingTargetDO.class, bid.getFinancingTargetId());
			if(target != null && target.getType().equalsIgnoreCase("CPB")) {
				LOG.info(String.format("【七夕活动】发放现金券，bid=[%s],标的id=[%s],type=[%s],period=[%s]", bid,bid.getFinancingTargetId(),target.getType(),target.getPeriod()));
				BigDecimal exprBuyAmount = new BigDecimal(0);
				if(target.getPeriod() == 7) {
					exprBuyAmount = bid.getBuyAmount().multiply(BigDecimal.valueOf(1));
				} else if(target.getPeriod() == 15) {
					exprBuyAmount = bid.getBuyAmount().multiply(BigDecimal.valueOf(3));
				} else if(target.getPeriod() >= 30 && target.getPeriod() < 60) {
					exprBuyAmount = bid.getBuyAmount().multiply(BigDecimal.valueOf(6));
				} else if(target.getPeriod() >= 60 && target.getPeriod() < 80) {
					exprBuyAmount = bid.getBuyAmount().multiply(BigDecimal.valueOf(15));
				} else if(target.getPeriod() >= 80) {
					exprBuyAmount = bid.getBuyAmount().multiply(BigDecimal.valueOf(30));
				}
				
				FinancingTargetDO exprTarget = financingTargetService.find(FinancingTargetConstant.TAG_ACT_EXPR, exprBuyAmount);
				RewardBidService.BuyParam buyParam = new RewardBidService.BuyParam();
				buyParam.setBuyAmount(exprBuyAmount);
				buyParam.setTargetId(exprTarget.getId());
				buyParam.setUserId(bid.getBidUserId());
				return rewardBidService.doBuy(buyParam);
			}
		}
		return false;
	}
}
